package com.android.equipment.ui.work

import android.annotation.SuppressLint
import android.os.Bundle
import com.android.equipment.R
import com.android.equipment.adapter.HistoryAlamAdapter
import com.android.equipment.base.BaseActivity
import com.android.equipment.base.BaseApplication
import com.android.equipment.dao.operate.DaoHistoryAlam
import com.android.equipment.databinding.ActivityHistoryAlamBinding
import com.android.equipment.utils.ExcelUtil
import com.blankj.utilcode.util.ToastUtils
import com.gyf.immersionbar.ImmersionBar
import java.io.File
import java.io.IOException


class HistoryAlamActivity: BaseActivity<ActivityHistoryAlamBinding>() {
    private var workId: Long = -1
    override fun setLayoutContent() = ActivityHistoryAlamBinding.inflate(layoutInflater)

    private val historyAlamAdapter: HistoryAlamAdapter by lazy { HistoryAlamAdapter(R.layout.item_history_alam) }


    override fun initView(savedInstanceState: Bundle?) {
        workId = intent.getLongExtra("workId", -1)

        binding.mTitleBar.rightTitle = "导出数据"

        binding.mTitleBar.leftView.setOnClickListener {
            mSwipeBackHelper.backward()
        }

        binding.mTitleBar.rightView.setOnClickListener {
            if (historyAlamAdapter.data.isNotEmpty()){
                exportExcel()
            }


        }
    }

    override fun initData() {
        val historyAlamList = DaoHistoryAlam.getInstance().getHistoryAlamByWorkId(workId)
        binding.rvHistoryAlam.adapter = historyAlamAdapter
        if (historyAlamList.isNotEmpty()){
            historyAlamAdapter.setList(historyAlamList)
        }
    }

    override fun setStatusBar() {
        ImmersionBar.with(this)
            .statusBarColor(R.color.F8F9FA)
            .statusBarDarkFont(true)
            .titleBar(binding.mTitleBar)
            .init()
    }

    @SuppressLint("SetTextI18n")
    private fun exportExcel() {
        val file = File(getExternalFilesDir(null), getString(R.string.app_name))
        if (!file.exists()) {
            file.mkdirs()
        }

        val excelFileName = "/${System.currentTimeMillis()}.xls"
        val title = arrayOf(
            "作业名称",
            "设备名称",
            "设备号",
            "节点",
            "节点描述",
            "节点值",
            "作业人",
            "报警时间",
            "恢复时间"
        )


        val filePath: String = file.absolutePath + excelFileName
        try {
            ExcelUtil.initExcel(filePath, title)
            ExcelUtil.writeObjListToExcel<Any>(historyAlamAdapter.data.toList(), filePath, this)
            ToastUtils.showLong("excel已导出至：$filePath")
            binding.tvAddress.text = "excel已导出至：$filePath"
        } catch (e: IOException) {
            e.printStackTrace()
            ToastUtils.showLong("导出失败：" + e.message)
        }
    }
}